package com.tedu.weibotest.controller;


import com.tedu.weibotest.mapper.UserMapper;
import com.tedu.weibotest.pojo.dto.UserLoginDTO;
import com.tedu.weibotest.pojo.dto.UserRegDTO;
import com.tedu.weibotest.pojo.entity.User;
import com.tedu.weibotest.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("v1/users")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    // 注册  状态码1：注册成功，2：用户名已存在 0：注册失败
    @PostMapping("/reg")
    public int insert(@RequestBody UserRegDTO userRegDTO){
        User userfind=userMapper.selectByUsername(userRegDTO.getUsername());
        if (userfind!=null){
            return 2;
        }
        User user=new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        int num=userMapper.insert(user);
        return num>0?1:0;
    }


    // 登录  状态码1：登录成功，2：密码错误，3：用户名不存在
    @PostMapping("/login")
    public int login(@RequestBody UserLoginDTO userLoginDTO , HttpSession session){
        User user=userMapper.selectByUsername(userLoginDTO.getUsername());
        if (user!=null){
            if (userLoginDTO.getPassword().equals(user.getPassword())){
                // 存入session中，用于记录用户的登录状态
                session.setAttribute("user",user);
                return 1;
            }else {
                return 2;
            }
        }else {
            return 3;
        }
    }

    // 获取用户的登录状态
    @GetMapping("/currentUser")
    public UserVO currentUser(HttpSession session){
        User user=(User) session.getAttribute("user");
        if (user!=null){
            UserVO userVO=new UserVO();
            BeanUtils.copyProperties(user,userVO);
            return userVO;
        }else {
            return null;
        }

    }

    // 退出登录
    @GetMapping("/logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }




}
